﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RuiXinCoffee.DAL;
using RuiXinCoffee.Model;
using RuiXinCoffee.Utils;

namespace RuiXinCoffee.BLL
{
    internal class ShoppingCartService
    {
        //单例实例
        private static readonly Lazy<ShoppingCartService> _instance =
            new Lazy<ShoppingCartService>(() => new ShoppingCartService());

        public static ShoppingCartService Instance => _instance.Value;

        private OrderDAO orderDAO = new OrderDAO();

        //私有构造函数防止外部实例化
        private ShoppingCartService()
        {
            Orders = new List<OrderInfo>();
            //从数据库加载待付款订单
            LoadPendingOrders();
        }

        //购物车数据存储
        public List<OrderInfo> Orders { get; private set; }

        //从数据库加载待付款订单
        public void LoadPendingOrders()
        {
            try
            {
                //清空当前购物车
                Orders.Clear();
                
                //获取所有待付款订单（OrderStatus = 0）
                List<OrderInfo> pendingOrders = orderDAO.GetOrdersByStatus(0);
                
                //将待付款订单添加到购物车
                if (pendingOrders != null && pendingOrders.Count > 0)
                {
                    Orders.AddRange(pendingOrders);
                }
                
                //触发购物车更新事件
                CartUpdated?.Invoke();
            }
            catch (Exception ex)
            {
                throw new BusinessException("加载购物车失败", ex);
            }
        }

        //添加商品到购物车
        public void AddToCart(OrderInfo orderInfo)
        {
            try
            {
                //添加新商品
                Orders.Add(orderInfo);

                //触发购物车更新事件
                CartUpdated?.Invoke();
            }
            catch (Exception ex)
            {
                throw new BusinessException("添加商品到购物车失败", ex);
            }
        }

        //移除商品
        public void RemoveFromCart(OrderInfo orderInfo)
        {
            try
            {
                var item = Orders.FirstOrDefault(o => o.OrderId == orderInfo.OrderId);
                if (item != null)
                {
                    //从数据库中删除
                    orderDAO.DeleteOrder(item.OrderId);
                    
                    //从购物车中移除
                    Orders.Remove(item);
                    CartUpdated?.Invoke();
                }
            }
            catch (Exception ex)
            {
                throw new BusinessException("从购物车移除商品失败", ex);
            }
        }

        //清空购物车
        public void ClearCart()
        {
            try
            {
                //从数据库中删除所有待付款订单
                foreach (var order in Orders)
                {
                    orderDAO.DeleteOrder(order.OrderId);
                }
                
                Orders.Clear();
                CartUpdated?.Invoke();
            }
            catch (Exception ex)
            {
                throw new DatabaseException("清空购物车失败", ex);
            }
        }
        
        //更新所有订单为已支付状态
        public bool UpdateAllOrdersAsPaid()
        {
            try
            {
                foreach (var order in Orders)
                {
                    orderDAO.UpdateOrderStatus(order.OrderId, 1); //更新为已支付状态
                }
                
                //清空购物车
                Orders.Clear();
                CartUpdated?.Invoke();
                return true;
            }
            catch (Exception ex)
            {
                throw new DatabaseException("更新订单状态失败", ex);
            }
        }
        
        //获取商品总数量
        public int getTotal()
        {
            int total = 0;
            foreach (var item in Orders)
            {
                total += item.Quantity;
            }
            return total;
        }
        
        //计算总价
        public decimal CalculateTotal()
        {
            return Orders.Sum(item => item.Price * item.Quantity);
        }

        public event Action CartUpdated;
    }
}
